<?php
namespace Admin\Controller;
use Think\AjaxPage;
use Think\Db;

class CouponController extends BaseController {
    /**----------------------------------------------*/
     /*                优惠券控制器                  */
    /**----------------------------------------------*/
    /*
     * 优惠券类型列表
     */
    public function index(){
        //获取优惠券列表
        
    	$count =  M('coupon')->count();
    	$Page = new \Think\Page($count,10);        
        $show = $Page->show();
        $lists = M('coupon')->order('add_time desc')->limit($Page->firstRow.','.$Page->listRows)->select();

        $store_id = get_arr_column($lists,'store_id');
		if(empty($store_id)){
			$store = '';
		}else{
			$store= M('store')->where("store_id in (".implode(',', $store_id).")")->getField('store_id,store_name');
		}
        
		
        $this->assign('store',$store);
        $this->assign('lists',$lists);
        $this->assign('page',$show);// 赋值分页输出   
        $this->assign('coupons',C('COUPON_TYPE'));
        $this->display();
    }

    /*
     * 添加编辑一个优惠券类型
     */
    public function coupon_info(){
        if(IS_POST){
        	$data = I('post.');
        // 	dump($data);die;
            $data['send_start_time'] = strtotime($data['send_start_time']);
            $data['send_end_time'] = strtotime($data['send_end_time']);
            $data['use_end_time'] = strtotime($data['use_end_time']);
            $data['use_start_time'] = strtotime($data['use_start_time']);
            if(!empty($data['brand_id'])){
                $data['brand_id'] = json_encode($data['brand_id']);
            }else{
                $data['brand_id'] = '';
            }
            
            if($data['send_start_time'] > $data['send_end_time']){
                $this->error('发放日期填写有误');
            }
            // dump($data);
            // die;
            if(empty($data['id'])){
            	$data['add_time'] = time();
            	$row = M('coupon')->add($data);
            }else{
            	$row =  M('coupon')->where(array('id'=>$data['id']))->save($data);
            }
            if(!$row)
                $this->error('编辑代金券失败');
            $this->success('编辑代金券成功',U('Admin/Coupon/index'));
            exit;
        }
        $store= M('store')->field('store_id,store_name')->select();
        $this->assign('store',$store);
        $cid = I('get.id');
        $brandList = M('brand b')->field('b.id,b.name,c.name as cat_name')->join('ty_goods_category c on c.id = b.cat_id1','left')->group('name')->select();
        
        
        if($cid){
        	$coupon = M('coupon')->where(array('id'=>$cid))->find();
        	$coupon['brand_id'] = json_decode($coupon['brand_id'],true);
        	foreach ($brandList as $k=>$v){
        	    if(!in_array($v['id'],$coupon['brand_id'])){
        	        unset($brandList[$k]);
        	    }
        	}
        	sort($brandList);
        // 	dump($brandList);
        	$this->assign('coupon',$coupon);
        }else{
        	$def['send_start_time'] = strtotime("+1 day");
        	$def['send_end_time'] = strtotime("+1 month");
        	$def['use_start_time'] = strtotime("+1 day");
        	$def['use_end_time'] = strtotime("+2 month");
        	$this->assign('coupon',$def);
        }     
        $this->assign('brandList',$brandList);
        $this->display();
    }
    /*
    * 搜索品牌分類
    */  
    
    public function search_brand(){
    
        // $name = I('name');
    
    // 	if(!empty($goods_id)){
    // 		$where .= " and goods_id not in ($goods_id) ";
    // 	}
    // 	I('intro')  && $where = "$where and ".I('intro')." = 1";
    // 	if(I('cat_id')){
    // 		$this->assign('cat_id',I('cat_id'));
    // 		$grandson_ids = getCatGrandson(I('cat_id'));
    // 		$where = " $where  and cat_id in(".  implode(',', $grandson_ids).") "; // 初始化搜索条件
    // 	}
    // 	if(I('brand_id')){
    // 		$this->assign('brand_id',I('brand_id'));
    // 		$where = "$where and brand_id = ".I('brand_id');
    // 	}
        $where = '';
    	if(!empty(I('keywords')))
    	{
    		$this->assign('keywords',I('keywords'));
    		$where = "b.name like '%".I('keywords')."%'" ;
    	}
    
    	$count = M('brand b')->field('b.id,b.name,c.name as cat_name')->join('ty_goods_category c on c.id = b.cat_id1','left')->where($where)->count();
    
    	$Page  = new \Think\Page($count,20);
    	$goodsList = M('brand b')->field('b.id,b.name,c.name as cat_name')->join('ty_goods_category c on c.id = b.cat_id1','left')->where($where)->limit($Page->firstRow.','.$Page->listRows)->select();
    	$show = $Page->show();//分页显示输出
    	$this->assign('page',$show);//赋值分页输出
    	$this->assign('goodsList',$goodsList);
    	$this->display();
    }

    

    /*
    * 优惠券发放
    */
    public function make_coupon(){
        //获取优惠券ID
        $cid = I('get.id');
        $type = I('get.type');
        //查询是否存在优惠券
        $data = M('coupon')->where(array('id'=>$cid))->find();
        $remain = $data['createnum'] - $data['send_num'];//剩余派发量
    	if($remain<=0) $this->error($data['name'].'已经发放完了');
        if(!$data) $this->error("优惠券类型不存在");
        if($type != 4) $this->error("该优惠券类型不支持发放");
        if(IS_POST){
            $num  = I('post.num');
            if($num>$remain) $this->error($data['name'].'发放量不够了');
            if(!$num > 0) $this->error("发放数量不能小于0");
            $add['cid'] = $cid;
            $add['type'] = $type;
            $add['send_time'] = time();
            if($data['store_id'] > 0){
                $add['store_id'] = $data['store_id'];
            }
            for($i=0;$i<$num; $i++){
                do{
                    $code = get_rand_str(8,0,1);//获取随机8位字符串
                    $check_exist = M('coupon_list')->where(array('code'=>$code))->find();
                }while($check_exist);
                $add['code'] = $code;
                M('coupon_list')->add($add);
            }
            M('coupon')->where("id=$cid")->setInc('send_num',$num);
            adminLog("发放".$num.'张'.$data['name']);
            $this->success("发放成功",U('Admin/Coupon/index'));
            exit;
        }
        
        $this->assign('coupon',$data);
        $this->display();
    }
     /**
     * 导入会员
     */
    public function batch_update()
    {
        if(IS_POST){
            $excelFile = $_FILES['file']['tmp_name'];
            $data = $this->readFromExcel($excelFile);
            
          
        
            if($data && $data['data']){
                $errorNo = [];
                sort($data['data']);
                $cid = intval($data['data'][0][2]);
                $coupon = M('coupon')->where(['id'=>$cid])->find();
        		if($coupon['createnum']>0){
        			$remain = $coupon['createnum'] - $coupon['send_num'];//剩余派发量
        			if($remain<=0) $this->error($coupon['name'].'已经发放完了');
        		}
        		$able = count($data['data']);//本次发送量
        	
    			if($coupon['createnum']>0 && $remain<$able){
    				$this->error($coupon['name'].'派发量只剩'.$remain.'张');
    			}
                foreach($data['data'] as $item){
                    try{
                        if($item && $item[0]){ //有数据才添加
                            Db::startTrans(); //开启事务
                        	$time = time();
            				$gap = ($k+1) == $able ? '' : ',';
            				$user_id = intval($item[0]);
            				$insert .= "($cid,1,$user_id,$time)$gap";
                            Db::commit(); //事务提交
                        }
                    }catch(Exception $e){
                        Db::rollback();//事务回滚
                        Log::record($e->getMessage(),'ERR');
                        $errorNo[] = $item[0];
                    }
                }
                    if(!empty($insert)){
                        $insert = substr($insert,0,-1);
                    }
                	$sql = "insert into __PREFIX__coupon_list (`cid`,`type`,`uid`,`send_time`) VALUES $insert";
                	
        //     // dump($sql);exit;
        			M()->execute($sql);
        			M('coupon')->where("id=$cid")->setInc('send_num',$able);
        			adminLog("发放".$able.'张'.$coupon['name']);
                    

            }
            exit;

        }
        $this->display();
    }
    public function ajax_get_user(){
    	//搜索条件
    	$condition = array();
    	I('mobile') ? $condition['mobile'] = I('mobile') : false;
    	$nickname = I('nickname');
    	$biaoshi = I('biaoshi');
    	$biaoshi_xian = I('biaoshi_xian');
    	if(!empty($nickname)){
    		$condition['nickname'] = array('like',"%$nickname%");
    	}

    	if(!empty($biaoshi)){
    		$condition['biaoshi'] = array('like',"%$biaoshi%");
    	}
    	if(!empty($biaoshi_xian)){
    		$condition['biaoshi_xian'] = array('like',"%$biaoshi_xian%");
    	}
    	$model = M('users');
    	$count = $model->where($condition)->count();
    	$Page  = new AjaxPage($count,25);
    	foreach($condition as $key=>$val) {
    		$Page->parameter[$key] = urlencode($val);
    	}
    	$show = $Page->show();
    	$userList = $model->where($condition)->order("user_id desc")->limit($Page->firstRow.','.$Page->listRows)->select();
        
        $user_level = M('user_level')->getField('level_id,level_name',true);       
        $this->assign('user_level',$user_level);
    	$this->assign('userList',$userList);
    	$this->assign('page',$show);
    	$this->display();
    }
    
    public function send_coupon(){
    	$cid = I('cid');    	
    	if(IS_POST){
    		$level_id = I('level_id');
    		$user_id = I('user_id');
    		$insert = '';
    		$coupon = M('coupon')->where("id=$cid")->find();
    		if($coupon['createnum']>0){
    			$remain = $coupon['createnum'] - $coupon['send_num'];//剩余派发量
    			if($remain<=0) $this->error($coupon['name'].'已经发放完了');
    		}
    		$store_id = 0;
    		if($coupon['store_id'] > 0){
    		    $store_id = $coupon['store_id'];
    		}
    		if(empty($user_id) && $level_id>=0){
    			if($level_id==0){
    				$user = M('users')->where("is_lock=0")->select();
    			}else{
    				$user = M('users')->where("is_lock=0 and level_id=$level_id")->select();
    			}
    			if($user){
    				$able = count($user);//本次发送量
    				if($coupon['createnum']>0 && $remain<$able){
    					$this->error($coupon['name'].'派发量只剩'.$remain.'张');
    				}
    				foreach ($user as $k=>$val){
    					$user_id = $val['user_id'];
    					$time = time();
    					$gap = ($k+1) == $able ? '' : ',';
    					$insert .= "($cid,1,$user_id,$time,$store_id)$gap";
    				}
    			}
    		}else{
    			$able = count($user_id);//本次发送量
    			if($coupon['createnum']>0 && $remain<$able){
    				$this->error($coupon['name'].'派发量只剩'.$remain.'张');
    			}
    			foreach ($user_id as $k=>$v){
    				$time = time();
    				$gap = ($k+1) == $able ? '' : ',';
    				$insert .= "($cid,1,$v,$time,$store_id)$gap";
    			}
    		}
			$sql = "insert into __PREFIX__coupon_list (`cid`,`type`,`uid`,`send_time`,`store_id`) VALUES $insert";
            // dump($sql);exit;
			M()->execute($sql);
			M('coupon')->where("id=$cid")->setInc('send_num',$able);
			adminLog("发放".$able.'张'.$coupon['name']);
			$this->success("发放成功");
			exit;
    	}
    	$level = M('user_level')->select();
    	$this->assign('level',$level);
    	$this->assign('cid',$cid);
    	$this->display();
    }
    
    public function send_cancel(){
    	
    }

    /*
     * 删除优惠券类型
     */
    public function del_coupon(){
        //获取优惠券ID
        $cid = I('get.id');
        //查询是否存在优惠券
        $row = M('coupon')->where(array('id'=>$cid))->delete();
        if($row){
            //删除此类型下的优惠券
            M('coupon_list')->where(array('cid'=>$cid))->delete();
            $this->success("删除成功");
        }else{
            $this->error("删除失败");
        }
    }


    /*
     * 优惠券详细查看
     */
    public function coupon_list(){
        //获取优惠券ID
        $cid = I('get.id');
        $uid = I('uid');
        if(!empty($uid)){
            $where = ' and u.mobile = '.$uid;
        }
        //查询是否存在优惠券
        $check_coupon = M('coupon')->field('id,type')->where(array('id'=>$cid))->find();
        if(!$check_coupon['id'] > 0)
            $this->error('不存在该类型优惠券');
       
        //查询该优惠券的列表的数量
        $sql = "SELECT count(1) as c FROM __PREFIX__coupon_list  l ".
                "LEFT JOIN __PREFIX__coupon c ON c.id = l.cid ". //联合优惠券表查询名称
                "LEFT JOIN __PREFIX__order o ON o.order_id = l.order_id ".     //联合订单表查询订单编号
                "LEFT JOIN __PREFIX__users u ON u.user_id = l.uid WHERE l.cid = ".$cid.$where;    //联合用户表去查询用户名        
        
        $count = M()->query($sql);
        $count = $count[0]['c'];
    	$Page = new \Think\Page($count,10);
    	$show = $Page->show();
        
        //查询该优惠券的列表
        $sql = "SELECT l.*,c.name,o.order_sn,u.nickname FROM __PREFIX__coupon_list  l ".
                "LEFT JOIN __PREFIX__coupon c ON c.id = l.cid ". //联合优惠券表查询名称
                "LEFT JOIN __PREFIX__order o ON o.order_id = l.order_id ".     //联合订单表查询订单编号
                "LEFT JOIN __PREFIX__users u ON u.user_id = l.uid WHERE l.cid = ".$cid.$where.    //联合用户表去查询用户名
                " limit {$Page->firstRow} , {$Page->listRows}";
        $coupon_list = M()->query($sql);
        $this->assign('coupon_type',C('COUPON_TYPE'));
        $this->assign('type',$check_coupon['type']);       
        $this->assign('lists',$coupon_list);            	
    	$this->assign('page',$show);        
        $this->display();
    }
    
    /*
     * 删除一张优惠券
     */
    public function coupon_list_del(){
        //获取优惠券ID
        $cid = I('get.id');
        if(!$cid)
            $this->error("缺少参数值");
        //查询是否存在优惠券
         $row = M('coupon_list')->where(array('id'=>$cid))->delete();
        if(!$row)
            $this->error('删除失败');
        $this->success('删除成功');
    }

}